package com.example.shop.commodity.service;

import com.example.shop.base.BaseService;
import com.example.shop.commodity.dao.ShopCartDao;
import com.example.shop.commodity.dao.ShopCommodityDao;
import com.example.shop.commodity.entity.PayInfoDto;
import com.example.shop.commodity.entity.ShopCart;
import com.example.shop.commodity.entity.ShopCommodity;
import com.example.shop.commodity.entity.ShopOrder;
import com.example.shop.commodity.dao.ShopOrderDao;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * @author hcj
 * @date 2021-09-21 19:06:20
 */
@Service
public class ShopOrderService extends BaseService<ShopOrder, ShopOrderDao> {

    @Autowired
    private ShopCommodityDao commodityDao;
    @Autowired
    private ShopCartDao cartDao;
    static final SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmsss");

    public String getAddress(String uid) {
        ShopOrder shopOrder = dao.getAddress(uid);
        if (shopOrder == null) {
            return null;
        }
        return shopOrder.getAid() == null ? null : shopOrder.getAid();
    }

    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public int pay(PayInfoDto payInfoDto) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        ShopOrder order = dao.getById(payInfoDto.getId());

        String[] cids = order.getCid().split(",");
        for (String cid : cids) {
            String[] s = cid.split("-");
            int i = deduct(s);
            if (i == 0) {
                return i;
            }
        }

        order.setAid(mapper.writeValueAsString(payInfoDto));
        order.setStatus("1");
        order.setPayType(payInfoDto.getPayType());
        order.setPayTime(new Date());
        super.save(order);
        return 1;
    }

    private String createNum() {
        String s = sdf.format(new Date());
        s = s + (int) (Math.random() * 40) + 10 + (int) (Math.random() * 50) + 50;
        return s;
    }

    private int deduct(String[] s) {
        ShopCommodity commodity = commodityDao.getById(s[0]);
        if (commodity.getStock() > 0) {
            // 扣减库存
            int i = commodityDao.deduct(commodity.getId(), commodity.getV());
            if (i == 0) {
                deduct(s);
            }
            return i;
        }
        return 0;
    }


    public ShopOrder getById(String id) {
        return dao.getById(id);
    }

    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public String createOrder(String id, String uid) {
        ShopOrder order = new ShopOrder();
        ShopCommodity commodity = commodityDao.getById(id);

        order.setUid(uid);
        order.setNumber(1);
        order.setPayPrice(commodity.getPrice());

        List<String> list = new ArrayList<>();
        ObjectMapper mapper = new ObjectMapper();
        try {
            list.add(mapper.writeValueAsString(commodity));
        } catch (Exception e) {
            e.printStackTrace();
        }
        order.setStatus("0");
        order.setCommodity(list.toString());
        order.setCid(commodity.getId() + "-1-" + commodity.getPrice());
        order.setOrderNum(createNum());
        super.save(order);
        return order.getId();
    }

    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public String createOrder(ShopOrder order, String uid) {
        String cid = "";
        BigDecimal total = BigDecimal.ZERO;
        BigDecimal number = BigDecimal.ZERO;
        List<String> list = new ArrayList<>();
        ObjectMapper mapper = new ObjectMapper();
        //购物车结算id
        order.setNumber(order.getCartId().size());
        for (String s : order.getCartId()) {
            ShopCart cart = cartDao.getByOne(s, uid);
            ShopCommodity commodity = commodityDao.getById(cart.getCid());
            BigDecimal p = commodity.getPrice().multiply(new BigDecimal(cart.getNumber()));
            total = total.add(p);
            cid = cid + commodity.getId() + "-" + cart.getNumber() + "-" + commodity.getPrice() + ",";
            number = number.add(new BigDecimal(cart.getNumber()));
            cart.setStatus("1");
            cartDao.update(cart);
            try {
                list.add(mapper.writeValueAsString(commodity));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        order.setCid(cid);
        order.setUid(uid);
        order.setPayPrice(total);
        order.setNumber(number.intValue());
        order.setStatus("0");
        order.setCommodity(list.toString());
        order.setOrderNum(createNum());
        super.save(order);
        return order.getId();
    }
}